package me.shiqiang.im.service;

import com.sun.imageio.plugins.gif.GIFImageReader;
import com.sun.imageio.plugins.gif.GIFImageReaderSpi;
import com.tst.common.exception.ServiceException;
import com.tst.common.utils.OssUtils;
import me.shiqiang.im.dao.EmojiDao;
import me.shiqiang.im.dao.OfficialEmojiDao;
import me.shiqiang.im.domain.Emoji;
import me.shiqiang.im.domain.OfficialEmojiSeries;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.imageio.spi.ImageReaderSpi;
import javax.imageio.stream.FileImageInputStream;
import javax.imageio.stream.ImageOutputStream;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by John on 2018/6/13
 */
@Service
@CacheConfig(cacheManager = "GroupCacheManager", cacheNames = {"GROUP_CACHE"})
public class EmojiService {

    @Autowired
    EmojiDao emojiDao;

    @Autowired
    OfficialEmojiDao officialEmojiDao;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Cacheable(key = "'emoji.cache'+#groupId + #fileId")
    public String get(Long groupId, Long fileId) {
        if (groupId != null) {
            OfficialEmojiSeries emojiSeries = officialEmojiDao.findOne(groupId);
            Emoji emoji = emojiSeries.getEmojis().get(fileId);
            return emoji.getUrl();
        } else {
            Emoji emoji = emojiDao.findOne(fileId);
            return emoji.getUrl();
        }
    }

    public void saveOffical(MultipartFile[] multipartFiles, String seriesName) {
        OfficialEmojiSeries emojiSeries = new OfficialEmojiSeries();
        emojiSeries.setId(stringRedisTemplate.opsForValue().increment("officialEmojiSeries", 1));
        emojiSeries.setName(seriesName);

        Map map = new HashMap();

        InputStream inputStream = null;

        for (MultipartFile multipartFile : multipartFiles) {
            String[] fileName = multipartFile.getOriginalFilename().split("\\.");
            if (fileName.length <= 1) {
                throw new ServiceException("文件名不合法");
            }

            String postfix = fileName[1];
            String id = null;
            try {
                BufferedImage bufferedImage = ImageIO.read(multipartFile.getInputStream());
                if (bufferedImage == null) {
                    throw new ServiceException("非图片不可上传");
                }
                Long seq = stringRedisTemplate.opsForValue().increment("emoji", 1);
                id = "emoji" + seq + ".";

                inputStream = new ByteArrayInputStream(multipartFile.getBytes());

                OssUtils.upload(inputStream, "emoji/" + id + postfix);

                if (postfix.equalsIgnoreCase("gif")) {
                    File file = File.createTempFile(fileName[0], fileName[1]);
                    multipartFile.transferTo(file);

                    ImageReaderSpi readerSpi = new GIFImageReaderSpi();
                    GIFImageReader gifImageReader = (GIFImageReader) readerSpi.createReaderInstance();
                    gifImageReader.setInput(new FileImageInputStream(file));
                    int num = gifImageReader.getNumImages(true);
                    if (num > 1) {
                        BufferedImage read = gifImageReader.read(1);

                        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                        ImageOutputStream imageOutput = ImageIO.createImageOutputStream(byteArrayOutputStream);
                        ImageIO.write(read, "png", imageOutput);
                        inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
                    }

                    OssUtils.upload(inputStream, "thumbnail/" + id + "png");

                    //删除临时文件
                    file.delete();
                }

                if (fileName[0].contains("cover")) {
                    emojiSeries.setCoverUrl("emoji/" + id + postfix);
                    continue;
                }

                Emoji emoji = new Emoji();
                emoji.setId(seq);
                emoji.setUrl("emoji/" + id + postfix);
                emoji.setName(fileName[0]); //and so on..
                map.put(seq, emoji);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        emojiSeries.setEmojis(map);

        officialEmojiDao.save(emojiSeries);
    }


//    public void deleteOne(EmojiSearchVo vo) {
//        if (vo.getOfficial().equals(1)) {
//            OfficialEmojiSeries emojiGroup = officialEmojiDao.findOne(vo.getEmojiGroupId());
//            emojiGroup.getEmojis().remove(vo.getEmojiId());
//        }else {
//            emojiDao.delete(vo.getEmojiId());
//        }
//    }


    public String save(MultipartFile multipartFile) {
        String[] fileName = multipartFile.getOriginalFilename().split("\\.");
        if (fileName.length <= 1) {
            throw new ServiceException("文件名不合法");
        }

        String postfix = fileName[1];
        String id = null;
        try {
            BufferedImage bufferedImage = ImageIO.read(multipartFile.getInputStream());
            if (bufferedImage == null) {
                throw new ServiceException("非图片不可上传");
            }
            Long seq = stringRedisTemplate.opsForValue().increment("emoji", 1);
            id = "emoji" + seq + ".";
            InputStream inputStream = null;

            inputStream = new ByteArrayInputStream(multipartFile.getBytes());

            OssUtils.upload(inputStream, "emoji/" + id + postfix);

            if (postfix.equalsIgnoreCase("gif")) {
                File file = File.createTempFile(fileName[0], fileName[1]);
                multipartFile.transferTo(file);

                ImageReaderSpi readerSpi = new GIFImageReaderSpi();
                GIFImageReader gifImageReader = (GIFImageReader) readerSpi.createReaderInstance();
                gifImageReader.setInput(new FileImageInputStream(file));
                int num = gifImageReader.getNumImages(true);
                if (num > 1) {
                    BufferedImage read = gifImageReader.read(1);

                    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                    ImageOutputStream imageOutput = ImageIO.createImageOutputStream(byteArrayOutputStream);
                    ImageIO.write(read, "png", imageOutput);
                    inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
                }

                OssUtils.upload(inputStream, "thumbnail/" + id + "png");

                //删除临时文件
                file.delete();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return id;

    }


    //客户端展览下载界面
    public Iterable<OfficialEmojiSeries> getAllOffical() {
        return officialEmojiDao.findAll();
    }
}
